<?php

declare (strict_types=1);


namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Cache;
use think\facade\Event;

/**
 * 用户释放订单
 */
class UserRelease extends Base
{
    protected $name = 'user_release';

    protected $type = [
        'effective_time' => 'timestamp',
        'complete_time' => 'timestamp',
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'uid')->field('id,code,nickname,is_active');
    }

    public function getStatusNameAttr($v, $data)
    {
        $status = [
            1 => '锁仓中',
            2 => '释放中',
            3 => '已完成'
        ];

        return $status[$data['status']] ?? '锁仓中';
    }

    public function getDifferenceAttr($v, $data)
    {
        // 将字符串日期转换为时间戳
        $timestamp1 = $data['effective_time'];
        $timestamp2 = time();
        if ($timestamp1 > $timestamp2) {
            // 计算时间差
            $difference = $timestamp1 - $timestamp2;

            // 将时间差转换为天数
            return intval($difference / (60 * 60 * 24));
        }

        return 0;
    }

    public static function release($uid, $totalAmount, $source, $intro, $cate, $is_old = 0)
    {
        $data = parent::with(['user'])->where('surplus_amount', '>', 0)
            ->where('effective_time', '<=', time())
            ->where('uid', $uid)
            ->select();

        $resultAmount = 0;
        $surplus_amount = $totalAmount;
        $system = Cache::get('system');
        foreach ($data as $datum) {
            if ($datum->user->is_active != 2) continue;
            if ($surplus_amount > $datum->surplus_amount) {
                $surplus_amount = $totalAmount - $datum->surplus_amount;
                $amount = $datum->surplus_amount;
            } else {
                $amount = $surplus_amount;
                $surplus_amount = 0;
            }
            if ($amount > 0) {
                $datum->status = 2;
                $datum->release_amount += $amount;
                $datum->surplus_amount -= $amount;
                if ($datum->surplus_amount <= 0) {
                    $datum->complete_time = time();
                    $datum->status = 3;
                }
                $datum->save();
                $resultAmount += $amount;
            }
            if ($surplus_amount <= 0) break;
        }

        if ($resultAmount > 0) {
            $bonusAmount = round($resultAmount * $system['bonus_tp'], 2);
            if ($is_old) {
                $lockAmount = round($bonusAmount * $system['lock_release_tp'], 2);
                $confirmAmount = $bonusAmount - $lockAmount;
                if ($confirmAmount > 0) {
                    Target::Account()->basics($uid, 'confirm_right', $bonusAmount - $lockAmount, $intro, '+')
                        ->createBonus($bonusAmount, $source, $cate);
                }

                Target::Account()->basics($uid, 'lock_confirm_right', $lockAmount, $intro, '+')
                    ->createBonus($bonusAmount, $source, $cate);
            } else {
                Target::Account()->basics($uid, 'confirm_right', $bonusAmount, $intro, '+')
                    ->createBonus($resultAmount, $source, $cate);
            }
//
//            Target::Account()->basics($uid, 'coupon', $resultAmount, $intro, '-')
//                ->createNormal($source);
        }
        return $resultAmount;
    }

    /**
     * 每日自动释放0.3%
     * @return array
     */
    public static function autoRelease()
    {
        parent::startTrans();
        try {
            $curTime = strtotime(date('Y-m-d'));
            $data = parent::with(['user'])->where('surplus_amount', '>', 0)
                ->where('effective_time', '<=', $curTime)
                ->where('type', 3)
                ->select();
            $system = Cache::get('system');
            $resultAmount = 0;
            foreach ($data as $datum) {
                if (!empty($datum->next_time)) {
                    $next_time = strtotime(date('Y-m-d', $datum->next_time));
                    if ($next_time > $curTime) {
                        continue;
                    }
                }
                $amount = round($datum->amount * $system['shopping_release_tp'], 2);
                if ($amount > $datum->surplus_amount) {
                    $amount = $datum->surplus_amount;
                }
                if ($amount > 0) {
                    $datum->release_amount += $amount;
                    $datum->surplus_amount -= $amount;
                    $datum->status = 2;
                    if ($datum->surplus_amount <= 0) {
                        $datum->complete_time = time();
                        $datum->status = 3;
                    }
                    $datum->next_time = strtotime("+{$system['release_day']} day");
                    $datum->save();
                    $resultAmount += $amount;
                    $bonusAmount = round($amount * $system['bonus_tp'], 2);
                    $parent_id = User::where('id', $datum->uid)->value('parent_id', 0);
                    if ($parent_id > 0) {
                        $directAmount = round($amount * $system['direct_release_tp'], 2);
                        $resultAmount += self::release($parent_id, $directAmount, $datum->uid,
                            '直推加速释放', 5, $datum->is_old);
                    }
                    // 团队加速
                    // 释放
                    Relation::teamBonus($datum->uid, $amount, $datum->is_old);
                    if ($datum->is_old) {
                        $lockAmount = round($bonusAmount * $system['lock_release_tp'], 2);
                        $confirmAmount = $bonusAmount - $lockAmount;
                        if ($confirmAmount > 0) {
                            Target::Account()->basics($datum->uid, 'confirm_right', $confirmAmount, '释放', '+')
                                ->createBonus($bonusAmount, 0, 4);
                        }

                        Target::Account()->basics($datum->uid, 'lock_confirm_right', $lockAmount, '释放', '+')
                            ->createBonus($bonusAmount, 0, 4);
                    } else {
                        Target::Account()->basics($datum->uid, 'confirm_right', $bonusAmount, '释放', '+')
                            ->createBonus($amount, 0, 4);
                    }

//                    Target::Account()->basics($datum->uid, 'coupon', $amount, '释放', '-')
//                        ->createNormal();
                }
            }

            if ($resultAmount > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $resultAmount]);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '执行成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}